/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.framework.log.aspect;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.framework.log.annotation.Log;
import com.framework.log.enums.LogEnum;
import com.framework.log.model.SysLog;
import com.framework.log.utils.RequestHolder;
import com.framework.log.utils.StringUtils;
import com.framework.log.utils.ThrowableUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.framework.common.config.SessionUtil;
import com.framework.common.model.CommonUser;
import com.framework.log.service.ISysLogService;

import cn.hutool.json.JSONUtil;

/**
 * 
 * @author lusy
 *
 */
@Component
@Aspect
public class LogAspect {

    private final ISysLogService sysLogService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    public LogAspect(ISysLogService sysLogService) {
        this.sysLogService = sysLogService;
    }

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.framework.log.annotation.Log)")
    public void logPointcut() {
    }

    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        SysLog sysLog = setSysLog(joinPoint, LogEnum.LevelEnum.INFO);
        sysLogService.save(sysLog);
        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
    	SysLog sysLog = setSysLog(joinPoint, LogEnum.LevelEnum.ERROR);
        sysLog.setExceptionDetail(ThrowableUtil.getStackTrace(e));
        sysLogService.save(sysLog);
    }

    private SysLog setSysLog (JoinPoint joinPoint, LogEnum.LevelEnum levelEnum) {
    	MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log aopLog = method.getAnnotation(Log.class);
        String value = aopLog.value();

        String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
        
    	HttpServletRequest request = RequestHolder.getHttpServletRequest();
    	CommonUser userInfo = SessionUtil.getUser();
    	
    	Long time = System.currentTimeMillis() - currentTime.get();
    	currentTime.remove();
    	
    	SysLog sysLog = new SysLog();
    	sysLog.setLevel(levelEnum.name());
    	sysLog.setTime(time);
    	sysLog.setUserId(userInfo.getId());
    	sysLog.setUsername(userInfo.getName());
    	sysLog.setBrowser(StringUtils.getBrowser(request));
    	sysLog.setRequestIp(StringUtils.getIp(request));
    	sysLog.setParams(getParameter(method, joinPoint.getArgs()));
    	sysLog.setMethod(methodName);
    	sysLog.setDescription(value);
    	return sysLog;
    }
    
    private String getParameter(Method method, Object[] args) {
        Parameter[] parameters = method.getParameters();
        
        Map<String, Object> paramMap = Maps.newHashMap();
        
        for (int i = 0; i < parameters.length; i++) {
        	paramMap.put(parameters[i].getName(), args[i]);
        }
        return JSONUtil.toJsonStr(paramMap);
    }
}
